define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function($, undefined, Backend, Table, Form) {
    var Controller = {



        index: function() {
            Table.api.init({

                extend: {

                    index_url: 'pay/apply/index',

                    add_url: 'pay/apply/addapply' + location.search,
                    del_url: 'pay/apply/del',
                    view_url: 'pay/apply/view',
                    table: 'apply',

                }

            });
            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                detailView: true,
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id') },
                        {

                            field: 'project',

                            title: __('Project'),

                            formatter: function(project) {

                                if (project.name) {

                                    return project.name;

                                }

                                return '';

                            }

                        },
                        { field: 'amount', title: __('Amount') },
                        { field: 'addtime', title: __('Create_time'), formatter: Table.api.formatter.datetime, datetimeFormat: "YYYY-MM-DD" },

                        {
                            field: 'state',

                            title: __('Status'),

                            formatter: function(value) {

                                var statues = [__('VerifyNew'), __('VerifyWait'), __('VerifyPass'), __('VerifyRefuse')];

                                return Table.api.formatter.status(statues[value], statues)

                            }

                        },
                        {

                            field: 'operate',

                            title: __('Operate'),

                            table: table,

                            events: Table.api.events.operate,

                            formatter: function(value, row, index) {

                                return Table.api.formatter.operate.call(this, value, row, index);

                            },
                            buttons: [{

                                    name: 'view',

                                    title: '查看',

                                    icon: 'fa fa-eye',

                                    classname: 'btn btn-success btn-xs btn-view'

                                },
                                {

                                    name: 'del',

                                    title: '删除',

                                    icon: 'fa fa-trash',

                                    classname: 'btn btn-success btn-xs btn-dele'

                                },

                            ]
                        }

                    ]
                ],
                //注册加载子表的事件。注意下这里的三个参数！
                onExpandRow: function(index, row, $detail) {
                    initSubTable(index, row, $detail);
                }

            });
            // 为表格绑定事件
            Table.api.bindevent(table);
            table.on('click', '.btn-dele', function(e) {
                e.stopPropagation();
                var options = table.bootstrapTable('getOptions');
                var index = $(this).closest('tr').data('index');
                var data = table.bootstrapTable('getData');
                var id = data[index][options.pk];
                var state = data[index]['state'];
                if (state > 0) {
                    layer.msg('正在审核的项不能删除');
                    return;
                }
                //询问框

                layer.confirm('您确定要删除该项吗？', {
                    btn: ['确定', '取消'] //按钮
                }, function() {

                    $.post('pay/apply/dele', { id: id }, function(json) {
                        $('#table').bootstrapTable('refresh');
                        layer.closeAll();
                    });

                }, function() {
                    //layer.close();
                });

            });

            table.on('click', '.btn-view', function(e) {
                e.stopPropagation();
                var options = table.bootstrapTable('getOptions');
                var index = $(this).closest('tr').data('index');
                var data = table.bootstrapTable('getData');
                var id = data[index][options.pk]
                Fast.api.open(options.extend.view_url + (id ? "?id=" + id : ''), '查看申请单');


            });
        },
        addapply: function() {

            $('#subbutton').on('click', function() {
                submitData();
            });
            $('#bntaddpay').on('click', function() {
                var id = $('#projectid').val();
                Fast.api.open("pay/index/add?dialog=1&pid=" + (id ? id : '0'), '新增支出');

            });

            $('.delpaybnt').on('click', function() {
                var id = $(this).data('id');
                layer.confirm('是否删除该记录？', {
                        btn: ['确定', '取消'] //按钮
                    }, function() {


                        $.post('pay/index/del', { ids: id, action: 'del' }, function(json) {
                            if (json.code == 1) {
                                window.location.reload();
                            }
                        }, 'json');
                    },
                    function() {

                    }
                );

            })
            var submitData = function() {


                var amount_control = $("input[name='amount']");

                var payid_control = $("input[name='payid']");


                if (amount_control.size() == 0) {
                    layer.msg('没有需要提交的项');
                    return;
                }
                //var param = $('form').serializeArray();
                var param = {};
                param.log = new Array();
                param['projectid'] = $('#projectid').val();
                param['amount'] = 0;
                param['addamount'] = $('#addamount').val();
                $.each(amount_control, function(i, n) {
                    var c = parseFloat($(n).val());
                    if (isNaN(c)) {
                        c = 0;
                    }
                    var p = {};
                    p['amount'] = c;
                    p['payid'] = payid_control.eq(i).val();
                    param['log'].push(p);
                    param['amount'] += c;
                    //   param.push({ 'name': 'row[amount]', 'value': amount_control.eq(i).val() });
                    //param.push({ 'name': 'row[payid]', 'value': payid_control.eq(i).val() });
                });
                //console.log(param);

                $.post('pay/apply/addlog', param, function(json) {
                    if (json.code == 1) {
                        var applyid = json.data.applyid;
                        console.log(applyid);
                        //提交成功后直接提交流程
                        var param = { "row[applyid]": applyid }

                        $.post('flow/payapply/add?ids=45', param, function(json) {
                                if (json.code == 1) {
                                    Fast.api.close();
                                    window.parent.$("#table").bootstrapTable('refresh');
                                    // $.post('pay/apply/updateState', { 'id': applyid }, function(_json) {

                                    //     Fast.api.close();
                                    //     window.parent.$("#table").bootstrapTable('refresh');


                                    // });

                                } else {
                                    layer.msg('提交失败');
                                }
                            }, 'json')
                            // layer.msg('数据提交成功！');
                            // window.parent.$("#table").bootstrapTable('refresh');
                            // Fast.api.close();
                            // layer.closeAll();
                    }
                }, 'json')



            }
            Controller.api.bindevent();

        },

        edit: function() {


            Controller.api.bindevent();

        },
        view: function(id) {
            $('#submitflow').on('click', function() {

                var param = { "row[applyid]": $('#applyid').val() }

                $.post('flow/payapply/add?ids=41', param, function(json) {
                    if (json.code == 1) {
                        $.post('pay/apply/updateState', { 'id': $('#applyid').val() }, function(_json) {

                            Fast.api.close();
                            window.parent.$("#table").bootstrapTable('refresh');


                        });

                    } else {
                        layer.msg('提交失败');
                    }
                }, 'json')
            });

            Controller.api.bindevent();
        },
        api: {

            bindevent: function() {

                Form.api.bindevent($("form[role=form]"));

            }

        }

    }
    return Controller;
});


//初始化子表格(无线循环)
initSubTable = function(index, row, $detail) {
    var parentid = row.id;
    var cur_table = $detail.html('<table></table>').find('table');

    var html = "";
    html += "<table class='table table-bordered'>";
    html += "<thead>";
    html += "<tr style='height: 40px;'>";
    html += "<th>支出名称</th>";
    html += "<th>支出说明</th>";
    html += "<th>应付金额</th>";
    html += "<th>申请金额</th>";
    html += "</tr>";
    html += "</thead>";
    $.ajax({
        type: "get",
        url: "pay/apply/paylogList", //子表请求的地址
        data: { apid: row.id }, //我这里是点击父表后，传递父表列id和nama到后台查询子表数据
        async: false, //很重要，这里要使用同步请求
        success: function(data) {
            html += '<ul class="list-group" >';
            //遍历子表数据
            $.each(data.rows,
                function(n, value) {
                    html += "<tr  align='center'>" +
                        "<td>" + value.pay.summary + "</td>" +
                        "<td>" + value.pay.remark + "</td>" +
                        "<td>" + value.pay.amount + "</td>" +
                        "<td>应付：" + value.amount + "</td>" +
                        "</tr>";
                });
            html += '</table>';
            $detail.html(html); // 关键地方
        }
    });

}